#include "dyn_quad_qtrap.h"

qTrap::qTrap(Functor &_func, double _a, double _b, double _tol, int _maxIterations)
    : Quad(_func, _a, _b, _tol)
{
    setMaxIterations(_maxIterations);
}

double qTrap::doQuadrature()
{
    // We prepare values to hold the results.
    double s,sold=0.0;

    // We declare the driver.
    /*! \todo Instead of doing it like this,
     * it could be possible to template a generic
     * driver and choose it at compile-time, outside
     * the library. */
    TrapzDriver t(func, a, b);

    // We compute the successive refinements until convergence.
    for (int i=0;i<maxIterations;i++)
    {
        // We compute the integral.
        s = t.computeNextRefinement();

        // After a number of iterations (to avoid spurious
        // convergence), we check if we have converged.
        if (i>5)
            if (fabs(s-sold) < tol*fabs(sold) || (s == 0.0 && sold == 0.0))
                return s;

        sold=s;
    }
    cout << "The algorithm has not converged. " << endl;
    return 0.0;
}
